// nav/ActivityFragment.java
package com.xxxy.ljh.myapplication.nav;

import static android.app.Activity.RESULT_OK;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.provider.MediaStore;
import android.net.Uri;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.xxxy.ljh.myapplication.Adapter.ActivityAdapter;
import com.xxxy.ljh.myapplication.Dao.ActivityDao;
import com.xxxy.ljh.myapplication.Dao.UserPointsRecordDao;
import com.xxxy.ljh.myapplication.DaoImpl.UserPointsRecordDaoImpl;
import com.xxxy.ljh.myapplication.R;
import com.xxxy.ljh.myapplication.model.ActivityItem;
import com.xxxy.ljh.myapplication.model.PointSourceType;
import com.xxxy.ljh.myapplication.model.UserPointsRecord;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;


/**
 * ActivityFragment 是一个用于展示活动列表、支持搜索和每日签到功能的 Fragment。
 * 它负责从数据库加载活动数据，并提供 UI 控件供用户进行交互操作。
 */
public class ActivityFragment extends Fragment {

    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    private static final int CAMERA_REQUEST_CODE = 100;

    private String mParam1;
    private String mParam2;

    private RecyclerView recyclerView;
    private ActivityAdapter adapter;
    private List<ActivityItem> activityList;
    private EditText etSearch;
    private Button btnSignIn;
    private boolean isSignedIn = false;
    private ActivityDao activityDao;
    private UserPointsRecordDao pointsRecordDao;

    // 假设当前用户ID为1，实际应该从登录信息中获取
    private static final int CURRENT_USER_ID = 1;

    /**
     * 构造函数初始化 activityList 列表。
     */
    public ActivityFragment() {
        activityList = new ArrayList<>();
    }

    /**
     * 创建一个新的 ActivityFragment 实例。
     *
     * @param param1 参数1（保留字段）
     * @param param2 参数2（保留字段）
     * @return 新创建的 ActivityFragment 实例
     */
    public static ActivityFragment newInstance(String param1, String param2) {
        ActivityFragment fragment = new ActivityFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_activity, container, false);

        // 初始化数据库访问对象
        activityDao = new com.xxxy.ljh.myapplication.DaoImpl.ActivityDaoImpl(getActivity());
        pointsRecordDao = new UserPointsRecordDaoImpl(getActivity());

        // 初始化 RecyclerView 并设置适配器与布局管理器
        recyclerView = view.findViewById(R.id.recyclerView);
        if (recyclerView != null) {
            loadActivitiesFromDatabase();
            adapter = new com.xxxy.ljh.myapplication.Adapter.ActivityAdapter(getActivity(), activityList);
            recyclerView.setAdapter(adapter);
            recyclerView.setLayoutManager(new androidx.recyclerview.widget.GridLayoutManager(getActivity(), 2));
        }

        // 初始化搜索框和按钮控件
        etSearch = view.findViewById(R.id.et_search);
        Button btnSearch = view.findViewById(R.id.btn_search);
        btnSignIn = view.findViewById(R.id.btn_sign_in);

        // 设置搜索按钮点击事件监听器
        if (btnSearch != null) {
            btnSearch.setOnClickListener(v -> {
                if (etSearch != null) {
                    String keyword = etSearch.getText().toString().trim();
                    searchActivities(keyword);
                }
            });
        }

        // 设置签到按钮点击事件监听器
        if (btnSignIn != null) {
            btnSignIn.setOnClickListener(v -> {
                performSignInWithPoints(btnSignIn);
            });
        }

        return view;
    }

    /**
     * 从数据库加载所有活动数据到 activityList 中。
     * 若发生异常则弹出提示并打印错误堆栈。
     */
    private void loadActivitiesFromDatabase() {
        try {
            if (activityList == null) {
                activityList = new ArrayList<>();
            }

            activityList.clear();

            if (activityDao != null) {
                List<com.xxxy.ljh.myapplication.model.ActivityItem> dbActivities = activityDao.getAllActivities();
                if (dbActivities != null) {
                    activityList.addAll(dbActivities);
                }
            }
        } catch (Exception e) {
            if (getContext() != null) {
                Toast.makeText(getContext(), "加载活动数据失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
            }
            e.printStackTrace();
        }
    }

    /**
     * 根据关键字过滤活动列表并在适配器中更新显示结果。
     *
     * @param keyword 搜索关键词
     */
    private void searchActivities(String keyword) {
        if (keyword.isEmpty()) {
            // 如果搜索关键词为空，显示所有活动
            adapter.updateData(activityList);
            return;
        }

        List<ActivityItem> filteredList = new ArrayList<>();
        for (ActivityItem item : activityList) {
            if ((item.getTitle() != null && item.getTitle().contains(keyword)) ||
                    (item.getDescription() != null && item.getDescription().contains(keyword))) {
                filteredList.add(item);
            }
        }
        adapter.updateData(filteredList);
    }

    /**
     * 处理用户的签到逻辑，包括积分奖励和状态变更。
     *
     * @param btnSignIn 签到按钮视图对象
     */
    private void performSignInWithPoints(Button btnSignIn) {
        if (!isSignedIn) {
            // 检查今日是否已签到
            if (hasSignedInToday()) {
                Toast.makeText(requireContext(), "今日已签到！", Toast.LENGTH_SHORT).show();
                return;
            }

            // 执行签到并获得积分
            int earnedPoints = 10; // 每日签到固定10积分
            boolean success = addPointsToUser(earnedPoints, "每日签到");

            if (success) {
                isSignedIn = true;
                btnSignIn.setText("已签到 +" + earnedPoints + "积分");
                btnSignIn.setEnabled(false);

                // 显示积分获取提示对话框
                showPointEarnedDialog(earnedPoints);
            } else {
                Toast.makeText(requireContext(), "签到失败，请重试", Toast.LENGTH_SHORT).show();
            }
        }
    }

    /**
     * 判断当前用户在当天是否已经完成签到。
     * 注意：该方法目前仅作占位使用，在真实环境中应查询数据库确认。
     *
     * @return 是否已签到
     */
    private boolean hasSignedInToday() {
        // 简化实现：检查今天是否已经有签到记录
        // 实际项目中应该查询数据库判断当天是否有签到记录
        return false;
    }

    /**
     * 向用户账户添加指定数量的积分，并记录相关信息。
     *
     * @param points 积分数额
     * @param remark 积分来源备注
     * @return 添加成功返回 true，否则返回 false
     */
    private boolean addPointsToUser(int points, String remark) {
        try {
            UserPointsRecord record = new UserPointsRecord();
            record.setUserId(CURRENT_USER_ID);
            record.setTotalPoints(points);
            record.setSourceType(PointSourceType.DAILY_SIGN_IN);
            record.setRemark(remark);
            record.setOperateUserId(CURRENT_USER_ID);

            long result = pointsRecordDao.insertPointsRecord(record);
            return result > 0;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 弹出积分获取成功的提示对话框。
     *
     * @param points 获得的积分数额
     */
    private void showPointEarnedDialog(int points) {
        if (getContext() != null) {
            AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
            builder.setTitle("签到成功")
                    .setMessage("获得积分: " + points + "分\n积分可用于兑换礼品和服务！")
                    .setPositiveButton("确定", null)
                    .show();
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == CAMERA_REQUEST_CODE && resultCode == RESULT_OK) {
            Toast.makeText(requireContext(), "签到成功！", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        refreshActivityList();
    }

    /**
     * 刷新活动列表数据并通知适配器更新界面。
     */
    private void refreshActivityList() {
        loadActivitiesFromDatabase();
        if (adapter != null) {
            adapter.updateData(activityList);
        }
    }
}
